package com.snow.auth.controller;

import com.snow.annotation.SysLog;
import com.snow.auth.component.AuthComponent;
import com.snow.auth.entity.SystemTenant;
import com.snow.auth.service.SystemTenantService;
import com.snow.model.IdParams;
import com.snow.starter.SnowAutoConfiguration;
import com.snow.view.PageData;
import com.snow.view.WebResponse;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * 租户管理
 *
 * @author by 13119
 */
@AllArgsConstructor
@RestController
@RequestMapping("/system-tenant")
public class SystemTenantController {

    SystemTenantService systemTenantService;
    AuthComponent authComponent;
    SnowAutoConfiguration snowAutoConfiguration;

    @SysLog("创建租户")
    @PostMapping("/create")
    public WebResponse<SystemTenant> create(@RequestBody SystemTenant params) {
        return WebResponse.success(systemTenantService.save(params));
    }

    @SysLog("更新租户")
    @PostMapping("/update")
    public WebResponse<SystemTenant> update(@RequestBody SystemTenant params) {
        return WebResponse.success(systemTenantService.update(params));
    }

    @SysLog("删除租户")
    @PostMapping("/delete")
    public WebResponse<SystemTenant> delete(@RequestBody IdParams params) {
        return WebResponse.success(systemTenantService.delete(params.getId()));
    }

    @SysLog("分页查询租户列表")
    @PostMapping("/page")
    public WebResponse<PageData<SystemTenant>> page(@RequestBody SystemTenant params) {
        PageData<SystemTenant> result = systemTenantService.page(params);
        for (SystemTenant systemTenant : result.getList()) {
            systemTenant.setAccessSubdomain(snowAutoConfiguration.getWebScheme() + "://" + systemTenant.getSubdomain());
        }
        return WebResponse.success(result);
    }

    @PostMapping("/search")
    public WebResponse<List<SystemTenant>> search(@RequestBody SystemTenant params) {
        return WebResponse.success(systemTenantService.search(params));
    }

    @GetMapping("/get-tenant-info")
    public WebResponse<SystemTenant> getTenantInfo() {
        SystemTenant tenant = authComponent.getCurrentTenant();
        if (tenant != null) {
            tenant.setExpired(tenant.getExpiredDate().compareTo(new Date()) <= 0);
        }
        return WebResponse.success(tenant);
    }

}
